package com.ruoyi.crm.service.impl;

import java.util.List;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.Seq;
import com.ruoyi.crm.domain.*;
import com.ruoyi.crm.domain.vo.ContractVo;
import com.ruoyi.crm.mapper.ActivityMapper;
import com.ruoyi.crm.mapper.ContractMapper;
import com.ruoyi.crm.mapper.CourseMapper;
import com.ruoyi.crm.modules.mq.CrmMqProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.crm.mapper.BusinessMapper;
import com.ruoyi.crm.service.IBusinessService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 商机Service业务层处理
 *
 * @author ruoyi
 * @date 2023-03-16
 */
@Service
public class BusinessServiceImpl implements IBusinessService {
    @Resource
    private BusinessMapper businessMapper;

    @Resource
    private AssignRecordServiceImpl assignRecordService;

    @Resource
    private ContractMapper contractMapper;

    @Resource
    private CourseMapper courseMapper;

    @Resource
    private ActivityMapper activityMapper;

    @Resource
    private CrmMqProducer crmMqProducer;

    /**
     * 查询商机
     *
     * @param id 商机主键
     * @return 商机
     */
    @Override
    public Business selectBusinessById(Long id) {
        return businessMapper.selectBusinessById(id);
    }

    /**
     * 查询商机列表
     *
     * @param business 商机
     * @return 商机
     */
    @Override
    public List<Business> selectBusinessList(Business business) {
        return businessMapper.selectBusinessList(business);
    }

    /**
     * 新增商机
     *
     * @param business 商机
     * @return 结果
     */
    @Override
    public int insertBusiness(Business business) {
        business.setCreateBy(SecurityUtils.getUsername());
        business.setCreateTime(DateUtils.getNowDate());
        return businessMapper.insertBusiness(business);
    }

    /**
     * 修改商机
     *
     * @param business 商机
     * @return 结果
     */
    @Override
    public int updateBusiness(Business business) {
        business.setUpdateBy(SecurityUtils.getUsername());
        business.setUpdateTime(DateUtils.getNowDate());
        return businessMapper.updateBusiness(business);
    }

    /**
     * 批量删除商机
     *
     * @param ids 需要删除的商机主键
     * @return 结果
     */
    @Override
    public int deleteBusinessByIds(Long[] ids) {
        return businessMapper.deleteBusinessByIds(ids);
    }

    /**
     * 删除商机信息
     *
     * @param id 商机主键
     * @return 结果
     */
    @Override
    public int deleteBusinessById(Long id) {
        return businessMapper.deleteBusinessById(id);
    }

    /**
     * 1、修改商机状态为踢回公海
     * 2、修改分配记录latest为0
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public int giveBack(Long id) {
        assignRecordService.updateAssignRecord(id, AssignRecord.Type.BUSINESS.getValue(), AssignRecord.LatestStatus.STALE.getValue());

        Business business = businessMapper.selectBusinessById(id);
        business.setStatus(Clue.Status.FALSE.getValue());
        return businessMapper.updateBusiness(business);
    }

    /**
     * 捞取
     *
     * @param id
     * @return
     */
    @Override
    public int reset(Long id) {
        // 分配商机给当前用户
        AssignRecord assignRecord = new AssignRecord();
        assignRecord.setType(AssignRecord.Type.BUSINESS.name());
        assignRecord.setAssignId(id);
        assignRecord.setUserId(SecurityUtils.getUserId());
        assignRecord.setDeptId(SecurityUtils.getDeptId());
        assignRecord.setCreateTime(DateUtils.getNowDate());
        assignRecord.setUserName(SecurityUtils.getUsername());
        return assignRecordService.insertAssignRecord(assignRecord);
    }

    //    转合同
    @Transactional
    @Override
    public int transform(ContractVo contractVo) {
//        更新商机状态
        Business business = businessMapper.selectBusinessById(contractVo.getId());
        if (business.getCourseId() == null) {
            throw new RuntimeException("商机里面没有选择课程，无法转换客户合同！");
        }
        if (contractMapper.selectContractByNo(contractVo.getContractNo()) != null) {
            throw new RuntimeException("合同编号已经存在，无法转换客户合同！");
        }
        business.setStatus(Clue.Status.TO_CUSTOMER.getValue());
        business.setUpdateBy(SecurityUtils.getUsername());
        business.setUpdateTime(DateUtils.getNowDate());
        businessMapper.updateBusiness(business);
//        插入合同
        Contract contract = new Contract();
        BeanUtils.copyProperties(business, contract);
        contract.setBusinessId(contractVo.getId());
        contract.setContractNo(contractVo.getContractNo());
        contract.setFileName(contractVo.getFileName());
        contract.setPhone(contractVo.getPhone());
        contract.setEmail(contractVo.getEmail());

        String businessKey = Seq.getId();
        contract.setId(businessKey);
        contract.setCreateBy(SecurityUtils.getUsername());
        contract.setCreateTime(DateUtils.getNowDate());
        contract.setDeptId(SecurityUtils.getDeptId());
        // 状态（待审核：1，已通过：2，已驳回：3，全部完成：4）
        contract.setStatus("4");
        // 根据活动计算优惠后的金额
        setContractOrder(contract);
        contractMapper.insertContract(contract);
        // 通过邮件和短信发送序列号给用户
        crmMqProducer.produceContractCreatedMessage(contract);
        return 1;
    }

    private void setContractOrder(Contract contract) {
        Course course = courseMapper.selectCourseById(contract.getCourseId());
        contract.setCourseName(course.getName());
        Activity activity = null;
        if (contract.getActivityId() != null) {
            activity = activityMapper.selectActivityById(contract.getActivityId());
        }
        if (activity == null) {
            contract.setContractOrder(Float.valueOf(course.getPrice()));
        } else {
            if ("1".equals(activity.getType())) {
                contract.setDiscountType("课程折扣");
                contract.setContractOrder((float) (activity.getDiscount() / 10.0 * course.getPrice()));
            } else {
                contract.setDiscountType("代金劵");
                contract.setContractOrder(Float.valueOf(course.getPrice() - activity.getVouchers()));
            }
        }
    }
}
